package com.lkd.handler;


import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
@Slf4j
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)  // 补货工单主题
public class AutoSupplyTaskHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;


    @Override
    public void process(String jsonMsg) throws IOException {
        try {
            log.info("接收到自动创建补货工单的消息");
            SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
            VmVO vm = vmService.getVMInfo(supplyContract.getInnerCode());
            int userId = taskService.getLeastUser(vm.getRegionId(), false);
            if (userId == 0) return;
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY); // 补货工单
            taskViewModel.setAssignorId(0);
            taskViewModel.setDesc("自动创建补货工单");
            taskViewModel.setInnerCode(vm.getInnerCode());
            taskViewModel.setCreateType(0); // 自动工单
            taskViewModel.setUserId(userId);
            taskViewModel.setDetails(supplyContract.getSupplyData().stream().map(
                    supplyChannel -> {
                        TaskDetailsViewModel taskDetailsEntity = new TaskDetailsViewModel();
                        taskDetailsEntity.setChannelCode(supplyChannel.getChannelId());
                        taskDetailsEntity.setExpectCapacity(supplyChannel.getCapacity());
                        taskDetailsEntity.setSkuName(supplyChannel.getSkuName());
                        taskDetailsEntity.setSkuImage(supplyChannel.getSkuImage());
                        taskDetailsEntity.setSkuId(supplyChannel.getSkuId());
                        return taskDetailsEntity;
                    }
            ).collect(Collectors.toList()));
            taskService.createTask(taskViewModel);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
